<template>
  <view>
    <cu-custom bgColor="themeBgColor" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">发起拼团</block>
    </cu-custom>

    <view class="cu-card article">
      <view class="cu-item">
        <view class="content">
          <image :src="grouponInfo.picUrl" mode="aspectFill" class="row-img margin-top-xs"></image>
          <view class=" row-info block">
            <view class="text-black margin-top-sm overflow-2  text-bold">{{grouponInfo.goodsSpu.name}}</view>
            <view class="flex">
              <view class="text-black margin-top-xs overflow-2 text-gray text-sm">
                <text>{{ grouponInfo.grouponNum }}人团</text>
                <text class="margin-lr-xs">|</text> 已有{{
                  grouponInfo.launchNum
                }}人参与
              </view>
            </view>
            <view class="text-gray text-sm overflow-1" v-if="grouponInfo.goodsSpu&&grouponInfo.goodsSku.specs&&grouponInfo.goodsSku.specs.length > 0">{{specInfo}}</view>
            <view class="flex justify-start margin-top-lg align-center">
              <view class="text-price text-bold text-xl text-red">{{grouponInfo.grouponPrice}}</view>
              <view class="text-price text-decorat text-gray margin-left-sm">{{grouponInfo.goodsSku.salesPrice}}</view>
            </view>
          </view>
        </view>
        
      <view class="margin-top text-center">
        <button class="button1" @tap="toGroupon">发起拼团</button>
        <button class="button2 margin-top-sm" @tap="shareShowFun">分享</button>
      </view>
      <view class="text-gray text-sm margin-top text-center" v-if="grouponInfo.validBeginTime">{{ grouponInfo.validBeginTime }}至{{
          grouponInfo.validEndTime
        }}</view>
      </view>
    </view>
    <view class="cu-card mar-top-30" v-if="grouponUserList.length > 0">
      <view class="cu-item">
        <view class="cu-bar bg-white solid-bottom">
          <view class="action">
            <text class="cuIcon-titles themeColor"></text>已有{{ grouponUserTotal }}个拼单，可直接参与
          </view>
        </view>
        <view class="cu-list menu-avatar padding-right-xs">
          <view class="cu-item" v-for="(item, index) in grouponUserList" :key="index">
            <view class="cu-avatar round lg" :style="'background-image:url(' + item.headimgUrl + ');'"></view>
            <view class="content">
              <view class="flex">
                <view class="flex-sub">{{ item.nickName }}</view>
                <view class="flex-twice text-right text-sm">
                  <count-down class="text-red" :outTime="dateUtil.getOutTime(item.validEndTime)"
                    @countDownDone="countDownDone"></count-down>
                  <view>还差<text class="text-red">{{ item.grouponNum - item.havgrouponNum }}人</text>拼成</view>
                </view>
              </view>
            </view>
            <view class="action">
              <navigator class="cu-btn sm round text-white" style="background:#e65c53" hover-class="none"
                :url="'../groupon-user-detail/index?id=' + item.id+'&shopId='+shopInfo.id">去拼单</navigator>
            </view>
          </view>
          <view class="cu-load bg-white" v-if="loadmore" @tap="loadMore">加载更多</view>
        </view>
      </view>
    </view>
    <view class="cu-card mar-top-30">
      <view class="cu-item">
        <view class="bg-white solid-bottom padding-tb flex justify-center">
          <image src="../../../static/images/bargainRankLeft.png" style="width: 66rpx; height: 18rpx; margin: auto 0" />
          <view class="text-center text-lg text-bold themeColor margin-lr-sm">
            拼团规则</view>
          <image src="../../../static/images/bargainRankRight.png"
            style="width: 66rpx; height: 18rpx; margin: auto 0" />
        </view>
        <view class="padding">{{ grouponInfo.grouponRule }}</view>
      </view>
    </view>
    <view class="cu-card mar-top-30">
      <view class="cu-item">
        <view class="bg-white solid-bottom padding-tb flex justify-center">
          <image src="../../../static/images/bargainRankLeft.png" style="width: 66rpx; height: 18rpx; margin: auto 0" />
          <view class="text-center text-lg text-bold themeColor margin-lr-sm">
            商品详情</view>
          <image src="../../../static/images/bargainRankRight.png"
            style="width: 66rpx; height: 18rpx; margin: auto 0" />
        </view>
        <view class="bg-white">
          <jyf-parser :html="article_description"></jyf-parser>
        </view>
      </view>
    </view>
    <!-- html转wxml -->
    <!-- <view class="cu-bar bg-white tabbar border shop foot">
      <button open-type="contact" class="action bg-white">
        <view class="cuIcon-servicefill"></view>客服
      </button>
      </navigator>
      <view class="bg-orange submit" @tap="tobuy">
        <view class="grid col-1 text-center">
          <view class="text-price">{{ grouponInfo.goodsSku.salesPrice }}</view>
          <view>原价购买</view>
        </view>
      </view>
      <view :class="
          'bg-' + (grouponInfo.status == '1' ? 'blue' : 'gray') + ' submit'
        " @tap="toGroupon">
        <view class="grid col-1 text-center">
          <view class="text-price">{{ grouponInfo.grouponPrice }}</view>
          <view>{{
            grouponInfo.status == "0"
              ? "拼团未开始"
              : grouponInfo.status == "1"
              ? "发起拼团"
              : grouponInfo.status == "2"
              ? "拼团已过期"
              : ""
          }}</view>
        </view>
      </view>
    </view> -->

    <poster id="poster" ref="posterRef" :hide-loading="false" :preload="false" :config="posterConfig"
      @success="onPosterSuccess" @fail="onPosterFail"></poster>
    <view :class="'cu-modal bottom-modal ' + shareShow">
      <view class="cu-dialog">
        <view class="cu-bar bg-white">
          <view class="action text-green"></view>
          <view class="action text-red" @tap="shareHide">取消</view>
        </view>
        <view class="padding flex flex-direction">
          <share-friends :shareObj="{
              title: grouponInfo.shareTitle,
              desc: grouponInfo.goodsSpu.name,
              imgUrl: grouponInfo.picUrl,
            }"></share-friends>
          <button class="cu-btn margin-tb-sm lg round shadow-blur" :class="'bg-' + theme.themeColor"
            @tap="onCreatePoster">
            生成海报
          </button>
        </view>
      </view>
    </view>

    <view :class="'cu-modal ' + (posterShow ? 'show' : '')">
      <view class="cu-dialog show-bg">
        <view class="bg-white" style="height: calc(100vh - 200rpx)">
          <image :src="posterUrl" class="image-box"></image>
        </view>
        <view class="cu-bar bg-white solid-top show-btn">
          <view class="action margin-0 flex-sub" @tap="hidePosterShow">取消</view>

          <!-- #ifdef MP || APP-PLUS -->
          <view class="action margin-0 flex-sub solid-left text-red text-bold" @tap="savePoster">保存到相册</view>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <view class="action margin-0 flex-sub solid-left text-red text-bold" @tap="hidePosterShow">长按图片可保存或分享</view>
          <!-- #endif -->
        </view>
      </view>
    </view>
    <!-- #ifdef H5 || APP-PLUS -->
    <!-- 二维码组件，不显示，只用来生成二维码调用 说明文档 https://github.com/q310550690/uni-app-qrcode -->
    <!-- 该组件生成二维码时需要canvas元素装载,固直接引用组件没有使用js，效果一样 -->
    <tki-qrcode ref="qrCodeRef" :size="200" :val="curLocalUrl" :show="false" @result="startCreatePoster"
      icon="/static/public/logo.png"></tki-qrcode>
    <!-- #endif -->
  </view>
</template>

<script>
  import shopInfo from "@/components/shop-info/index";

  const util = require("@/utils/util.js");
  const { base64src } = require("@/utils/base64src.js");
  const app = getApp();
  import api from "@/utils/api";
  import dateUtil from "@/utils/dateUtil";
  import jweixin from "@/utils/jweixin";

  import poster from "@/components/wxa-plugin-canvas/poster/index";
  import countDown from "@/components/count-down/index";
  import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";
  import shareFriends from "@/components/share-friends/index.vue";

  export default {
    data() {
      return {
        CustomBar: this.CustomBar,
        theme: app.globalData.theme, //全局颜色变量
        dateUtil: dateUtil,
        grouponInfo: {
          goodsSku: {},
          goodsSpu: {
            freightTemplat: {},
          },
          shopInfo: {},
          grouponNum: 0,
        },
        disabled: false,
        page: {
          searchCount: true,
          current: 1,
          size: 5,
          ascs: "",
          //升序字段
          descs: "create_time",
        },
        parameter: {},
        grouponUserList: [],
        grouponUserTotal: 0,
        loadmore: true,
        shareShow: "",
        curLocalUrl: "",
        userInfo: null,
        modalRule: "",
        id: "",
        specInfo: "",
        posterUrl: "",
        posterShow: false,
        posterConfig: "",
        article_description: "",
        shopInfo: {}, //商铺信息
      };
    },
    components: {
      poster,
      countDown,
      shareFriends,
      tkiQrcode,
    },
    props: {},

    onShow() {
      app.initPage().then((res) => {
        this.grouponInfoGet();
        this.grouponUserList = [];
        this.grouponUserPageGrouponing();
      });
    },

    onLoad(options) {

      if (options.referee) {
        uni.setStorageSync('referee', options.referee)
      }
      if (options.shopId) {
        this.shopMethods(options.shopId);
      }
      // this.dateUtil = dateUtil;
      let id;

      if (options.scene) {
        //接受二维码中参数
        id = decodeURIComponent(options.scene);
      } else {
        id = options.id;
      }

      this.id = id;
      this.userInfo = uni.getStorageSync("user_info");
    },

    onShareAppMessage: function () {
      let grouponInfo = this.grouponInfo;
      let title = grouponInfo.shareTitle;
      let imageUrl = grouponInfo.picUrl;
      let path = "";
      path =
        "pages_grid/pages/groupon/groupon-detail/index?id=" + grouponInfo.id + "&referee=" + (uni.getStorageSync("user_info").refereeId || "") + "&shopId=" + this.shopInfo.id;
      console.log(`path`, path)
      return {
        title: title,
        path: path,
        imageUrl: imageUrl,
        success: function (res) {
          if (res.errMsg == "shareAppMessage:ok") {
            console.log(res.errMsg);
          }
        },
        fail: function (res) {
          // 转发失败
        },
      };
    },
    methods: {
      shopMethods(shopId) {
        api.shopInfoGet(shopId).then((res) => {
          this.shopInfo = res.data;
        });
      },
      //查询拼团信息
      grouponInfoGet() {
        api.grouponInfoGet(this.id).then((res) => {
          let grouponInfo = res.data;
          let goodsSku = grouponInfo.goodsSku;
          let specInfo = "";
          goodsSku.specs.forEach(function (specItem, index) {
            specInfo = specInfo + specItem.specValueName;

            if (goodsSku.specs.length != index + 1) {
              specInfo = specInfo + ";";
            }
          });
          this.grouponInfo = grouponInfo;
          this.specInfo = specInfo;
          this.article_description = grouponInfo.goodsSpu
            ? grouponInfo.goodsSpu.description
            : "";
        });
      },

      //拼团中记录列表
      grouponUserPageGrouponing() {
        api
          .grouponUserPageGrouponing(
            Object.assign(
              {
                grouponId: this.id,
                isLeader: "1",
                status: "0",
              },
              this.page,
              util.filterForm(this.parameter)
            )
          )
          .then((res) => {
            let grouponUserList = res.data.records;
            this.grouponUserList = [...this.grouponUserList, ...grouponUserList];
            this.grouponUserTotal = res.data.total;
            if (grouponUserList.length < this.page.size) {
              this.loadmore = false;
            }
          });
      },

      //原价购买
      tobuy() {
        let grouponInfo = this.grouponInfo;
        let goodsSpu = grouponInfo.goodsSpu;
        let goodsSku = grouponInfo.goodsSku;
        let specInfo = this.specInfo;
        /* 把参数信息异步存储到缓存当中 */

        uni.setStorage({
          key: "param-orderConfirm",
          data: [
            {
              spuId: goodsSpu.id,
              skuId: goodsSku.id,
              quantity: 1,
              salesPrice: goodsSku.salesPrice,
              spuName: goodsSpu.name,
              specInfo: specInfo,
              picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
              pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
              pointsDeductScale: goodsSpu.pointsDeductScale,
              pointsDeductAmount: goodsSpu.pointsDeductAmount,
              pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
              pointsGiveNum: goodsSpu.pointsGiveNum,
              freightTemplat: goodsSpu.freightTemplat,
              weight: goodsSku.weight,
              volume: goodsSku.volume,
              shopInfo: this.shopInfo,
            },
          ],
        });
        uni.navigateTo({
          url: "/pages/order/order-confirm/index",
        });
      },

      //发起拼团
      toGroupon(e) {
        let grouponInfo = this.grouponInfo;
        if (grouponInfo.status != "1") {
          uni.showToast({
            title: "暂时无法发起拼团！",
            icon: "none",
          });
          return;
        }
        let goodsSpu = grouponInfo.goodsSpu;
        let goodsSku = grouponInfo.goodsSku;

        if (grouponInfo.limitNum > 0) {
          // if (goodsSku.stock > 0) {
          /* 把参数信息异步存储到缓存当中 */
          uni.setStorage({
            key: "param-orderConfirm",
            data: [
              {
                spuId: goodsSpu.id,
                skuId: goodsSku.id,
                quantity: 1,
                salesPrice: grouponInfo.grouponPrice,
                spuName: goodsSpu.name,
                specInfo: this.specInfo,
                picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
                freightTemplat: goodsSpu.freightTemplat,
                weight: goodsSku.weight,
                volume: goodsSku.volume,
                orderType: "2",
                marketId: grouponInfo.id,
                shopInfo: this.shopInfo,
              },
            ],
          });
          uni.navigateTo({
            url: "../groupon-order-confirm/index",
          });
        } else {
          uni.showToast({
            title: "拼团商品库存不足",
            icon: "none",
            duration: 2000,
          });
        }
      },

      shareShowFun() {
        // #ifdef H5
        this.curLocalUrl = window.location.href;
        // #endif
        // #ifdef APP-PLUS
        this.curLocalUrl = util.setAppPlusShareUrl();
        // #endif
        this.shareShow = "show";
      },

      shareHide() {
        this.shareShow = "";
      },

      onPosterSuccess(e) {
        this.posterUrl = e;
        this.posterShow = true;
      },

      onPosterFail(err) {
        console.error(err);
      },

      hidePosterShow() {
        this.posterShow = false;
        this.shareShow = "";
      },
      /**
       * 异步生成海报
       */
      onCreatePoster() {
        // #ifdef MP
        api
          .qrCodeUnlimited({
            theme: app.globalData.theme, //全局颜色变量
            page: "pages/groupon/groupon-detail/index",
            scene: this.grouponInfo.id,
          })
          .then((res) => {
            base64src(res.data, (res) => {
              this.startCreatePoster(res);
            });
          });
        // #endif
        // #ifdef H5 || APP-PLUS
        uni.showLoading({
          title: "海报生成中",
          mask: true,
        });
        this.$refs.qrCodeRef._makeCode(); // H5需要先生成二维码后 才能生成海报
        // #endif
      },
      startCreatePoster(res) {
        // 开始 生成海报
        let desc = "长按识别小程序码";
        let shareImg = this.grouponInfo.picUrl;
        // #ifdef H5 || APP-PLUS
        desc = "长按识别二维码";
        // h5的海报分享的图片有的有跨域问题，所以统一转成base64的
        // 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
        shareImg = util.imgUrlToBase64(shareImg);
        // #endif
        let qrCode = res; //海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
        let posterConfig = {
          width: 750,
          height: 1280,
          backgroundColor: "#fff",
          debug: false,
          blocks: [
            {
              width: 690,
              height: 808,
              x: 30,
              y: 183,
              borderWidth: 2,
              borderColor: "#f0c2a0",
              borderRadius: 20,
            },
            {
              width: 634,
              height: 74,
              x: 59,
              y: 770,
              backgroundColor: "#fff",
              opacity: 0.5,
              zIndex: 100,
            },
          ],
          texts: [
            {
              x: 30,
              y: 113,
              baseLine: "top",
              text: this.grouponInfo.shareTitle,
              fontSize: 38,
              color: "#080808",
            },
            {
              x: 92,
              y: 810,
              fontSize: 38,
              baseLine: "middle",
              text: this.grouponInfo.goodsSpu.name,
              width: 570,
              lineNum: 1,
              color: "#080808",
              zIndex: 200,
            },
            {
              x: 59,
              y: 895,
              baseLine: "middle",
              text: [
                {
                  text: "拼团价",
                  fontSize: 28,
                  color: "#ec1731",
                },
                {
                  text: "¥" + this.grouponInfo.grouponPrice,
                  fontSize: 36,
                  color: "#ec1731",
                  marginLeft: 30,
                },
              ],
            },
            {
              x: 522,
              y: 895,
              baseLine: "middle",
              text: "原价 ¥" + this.grouponInfo.goodsSku.salesPrice,
              fontSize: 28,
              color: "#929292",
            },
            {
              x: 59,
              y: 945,
              baseLine: "middle",
              text: [
                {
                  text: this.grouponInfo.goodsSpu.sellPoint,
                  fontSize: 28,
                  color: "#929292",
                  width: 570,
                  lineNum: 1,
                },
              ],
            },
            {
              x: 360,
              y: 1065,
              baseLine: "top",
              text: desc,
              fontSize: 38,
              color: "#080808",
            },
            {
              x: 360,
              y: 1123,
              baseLine: "top",
              text: "快来和我一起拼一单吧！",
              fontSize: 28,
              color: "#929292",
            },
          ],
          images: [
            {
              width: 634,
              height: 634,
              x: 59,
              y: 210,
              url: shareImg,
            },
            {
              width: 220,
              height: 220,
              x: 92,
              y: 1020,
              url: qrCode,
            },
          ],
        };
        let userInfo = uni.getStorageSync("user_info");

        if (userInfo && userInfo.headimgUrl) {
          //如果有头像则显示
          posterConfig.images.push({
            width: 62,
            height: 62,
            x: 30,
            y: 30,
            borderRadius: 62,
            url: userInfo.headimgUrl,
          });
          posterConfig.texts.push({
            x: 113,
            y: 61,
            baseLine: "middle",
            text: userInfo.nickName,
            fontSize: 32,
            color: "#8d8d8d",
          });
        }
        this.posterConfig = posterConfig;
        this.posterShow = true;
        this.$refs.posterRef.onCreate(false, this.posterConfig); // 入参：true为抹掉重新生成
      },
      //点击保存到相册
      savePoster: function () {
        var that = this;
        uni.saveImageToPhotosAlbum({
          filePath: that.posterUrl,

          success(res) {
            uni.showModal({
              content: "图片已保存到相册，赶紧晒一下吧~",
              showCancel: false,
              confirmText: "好的",
              confirmColor: "#333",
              success: function (res) {
                if (res.confirm) {
                  /* 该隐藏的隐藏 */
                  that.shareShow = "";
                }
              },
              fail: function (res) {
                console.log(res);
              },
            });
          },
        });
      },

      ruleShow() {
        this.modalRule = "show";
      },
      ruleHide() {
        this.modalRule = "";
      },
      countDownDone() {
        this.onLoad();
      },
    },
  };
</script>
<style scoped>
  .bg-themeColor {
    background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 100%);
    color: #fff;
  }
  .button1 {
  width: 636rpx;
  height: 70rpx;
  line-height: 70rpx;
  background: linear-gradient(180deg, #ffa56f 0%, #ff6a4b 39%, #f43e36 100%);
  border-radius: 28px;
  font-size: 28rpx;
  letter-spacing: 1px;
  color: #ffffff;
}
.button2 {
  width: 636rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 28px;
  border: 1px solid #f43e36;
  background: #ffffff;
  color: #f43e36;
  letter-spacing: 1px;
}
button::after{
  border:none
}
</style>
<style>
  .themeColor {
    color: #e65c53;
  }
  .themeBgColor {
    background: #e65c53;
    color: #fff;
  }

.row-img {
    width: 230rpx !important;
    height: 230rpx !important;
  border-radius: 10rpx;
  margin-top:20rpx
}

  .cu-bar.tabbar.shop .action {
    width: unset;
  }

  .to-down {
    margin-top: 120rpx;
  }

  .share {
    width: 580rpx;
    height: 76rpx;
  }

  .show-bg {
    height: 84%;
    margin-top: 120rpx;
  }

  .image-box {
    height: 90%;
  }

  .show-btn {
    margin-top: -130rpx;
  }
</style>